package com.juejin.www.exception;

import com.juejin.www.model.DTO.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * 全局异常处理器
 * @author Jacky
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result ex(Exception e){
        e.printStackTrace();
        // 指定文件路径
        String filePath = "C:\\Users\\Jacky\\DataExcavteTest\\juejin\\exception.txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            // 写入异常信息，包括异常类型和异常消息
            writer.write("异常时间: " + LocalDateTime.now());
            writer.newLine();
            writer.write("异常类型: " + e.getClass().getName());
            writer.newLine();
            writer.write("异常消息: " + e.getMessage());
            writer.newLine();
            // 如果需要，还可以写入堆栈跟踪
            writer.write("堆栈跟踪:");
            e.printStackTrace(new PrintWriter(writer));
            writer.newLine();
            writer.newLine(); // 添加空行以便区分不同的异常记录
        } catch (IOException ex) {
            // 处理文件写入时可能发生的异常
            ex.printStackTrace();
        }
        return Result.error("操作失败，请联系管理员！");
    }
}
